package sanshi.contect.proxy.v3;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        Tank tank = new Tank();

        System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");

        /**
         * 方式一：在另一个类中去实现InvocationHandler接口
         */
//        Movable movable = (Movable) Proxy.newProxyInstance(
//                Tank.class.getClassLoader(),
//                new Class[]{Movable.class},
//                new LogHandler(tank));
//        movable.move();

        /**
         * 使用匿名实现类的匿名对象
         */
        Movable m = (Movable) Proxy.newProxyInstance(
                Tank.class.getClassLoader(),
                new Class[]{Movable.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("method: " + method.getName() + " start!!");
                        Object invoke = method.invoke(tank, args);
                        System.out.println("method: " + method.getName() + " end!!!!");
                        return invoke;
                    }
                }
        );

        m.move();

//        class LogHandlerOne implements InvocationHandler{
//
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                System.out.println("method: " + method.getName() + " start!!");
//                Object invoke = method.invoke(proxy, args);
//                System.out.println("method: " + method.getName() + " end!!!!");
//                return invoke;
//            }
//        }
//
//        /**
//         * 使用内部类
//         */
//        Movable m2 = (Movable) Proxy.newProxyInstance(Tank.class.getClassLoader(), new Class[]{Movable.class}, new LogHandlerOne());
//        m2.move();


    }
}
